package com.houcine.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public abstract class GenericJPADAO <T, ID extends Serializable > {

	private Class<T> persistentClass = figureOutPersistentClass();

    private Class<T> figureOutPersistentClass() {
        Class<T> clazz = (Class<T>)((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[0];
        return clazz;
    }
	
	protected EntityManager em;
	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
	public EntityManager getEntityManager() {
		return em;
	}
	
	public void save(T entity) {
		 em.merge(entity);
	}
	
	public void delete(T entity) {
		getEntityManager().remove(entity);
	}
	
	public T getById(Object id) {
		return getEntityManager().find(persistentClass, id);
		
	}
	
}
